import { isFunction } from 'lodash-es';

import type { BasicListProps } from '@/components/list/props';
import type { FormActionType } from '@/components/form';
import { useModal } from '@/components/modal';

export function useListCrud(
  props: BasicListProps,
  formInstance: Ref<FormActionType | undefined>,
  fetch: () => Promise<void>,
) {
  // TODO 处理schemas
  const formScene = ref<'create' | 'modify'>('create');

  const [
    modalRegister,
    { openModal, closeModal, setProps, setLoading },
  ] = useModal({});

  /**
   * 新增
   */
  function handleCreate() {
    setProps({
      title: props.title ? `新增${props.title}` : '新增',
    });
    formScene.value = 'create';
    openModal();
    setLoading(false);
  }

  /**
   * 编辑
   */
  function handleModify(item: Recordable) {
    setProps({
      title: props.title ? `编辑${props.title}` : '编辑',
    });
    openModal();
    nextTick().then(() => {
      formInstance.value?.setFieldsValue(item);
    });
    formScene.value = 'modify';
  }

  /**
   * 提交表单
   */
  async function handleSubmit() {
    // TODO 校验表单
    const formData = formInstance.value?.getFieldsValue();
    if (formScene.value === 'create' && isFunction(props.createRequest)) {
      try {
        await props.createRequest(formData);
        closeModal();
        await fetch();
      } finally {
        setLoading(false);
      }
    }

    if (formScene.value === 'modify' && isFunction(props.modifyRequest)) {
      try {
        await props.modifyRequest(formData);
        closeModal();
        await fetch();
      } finally {
        setLoading(false);
      }
    }
  }

  /**
   * 删除
   */
  async function handleDelete(item: Recordable) {
    const key = item[props.deleteKey ?? 'id'];
    if (isFunction(props.deleteRequest)) {
      await props.deleteRequest(key);
      await fetch();
    }
  }

  return {
    modalRegister,
    handleCreate,
    handleModify,
    handleDelete,
    handleSubmit,
  };
}
